package dnl.confij.props;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

import dnl.confij.ConfigException;
import dnl.confij.Configuration;

/**
 * Implements a properties configuration.
 * 
 * @author <a href="mailto:daniel.or@gmail.com">Daniel Or</a>
 * 
 */
public class PropertiesConfiguration extends Configuration {

	/**
	 * 
	 * Constructs a new <code>PropertiesConfiguration</code> using the given
	 * properties file.
	 * 
	 * @param propertiesFile
	 * @throws ConfigException
	 */
	public PropertiesConfiguration(File propertiesFile) throws ConfigException {
		this(propertiesFile, false, null);
	}

	/**
	 * 
	 * Constructs a new <code>PropertiesConfiguration</code> using the given
	 * properties file and the given charset.
	 * 
	 * @param propertiesFile
	 * @param charset
	 *            a character set that corresponds to the file's encoding.
	 * @throws ConfigException
	 */
	public PropertiesConfiguration(File propertiesFile, String charset)
			throws ConfigException {
		this(propertiesFile, false, charset);
	}

	/**
	 * 
	 * Constructs a new <code>PropertiesConfiguration</code> using the given
	 * properties file and the given charset.
	 * 
	 * @param propertiesFile
	 * @param createFileIfNeeded
	 *            creates the properties file if one does not exist.
	 * @param charset
	 *            a character set that corresponds to the file's encoding.
	 * @throws ConfigException
	 */
	public PropertiesConfiguration(File propertiesFile,
			boolean createFileIfNeeded, String charset) throws ConfigException {
		if (createFileIfNeeded && !propertiesFile.exists()) {
			try {
				FileUtils.touch(propertiesFile);
			} catch (IOException e) {
				throw new ConfigException("Could not create file.", e);
			}
		}
		if (charset == null) {
			this.configSource = new PropertiesConfigurationSource(
					propertiesFile);
		} else {
			this.configSource = new PropertiesConfigurationSource(
					propertiesFile, charset);
		}
		this.configSource.loadConfiguration(this);
	}

}
